/*Renders the query results using 
GDI */
#include "..\ProcessHistory\MainFrm.h"
#include "screen.h"
#include "query.h"
#include "..\phshared\phshared.h"
#include "wtl\wtl.h"
#include "..\ProcessHistory\PHScroll.h"
#include "PH.h"
#include "gdiplus.h"

//using namespace Gdiplus;
using namespace boost::posix_time;
using namespace std;
using namespace boost;

PHDisplay phd;
extern PHQuery phq;
extern PH ph_instance;

void DrawLines(HDC hDC,RECT rcEvent,long lID)
{
	Gdiplus::Graphics graphics(hDC);
	/*Process Start*/
		
	Gdiplus::Color c;
	c.SetFromCOLORREF(0x00CC33);
	Gdiplus::Pen pen(c);
	pen.SetWidth(3);
	if(phd._clipped_left.find(lID)==phd._clipped_left.end() )
		graphics.DrawLine(&pen,rcEvent.left,rcEvent.top,rcEvent.left,rcEvent.bottom);
		
	//Process End
	c.SetFromCOLORREF(0x1111EE);
	pen.SetColor(c);

	//Don't draw end if clipped
	if(phd._clipped_right.find(lID)==phd._clipped_right.end() )
		graphics.DrawLine(&pen,rcEvent.right,rcEvent.top,rcEvent.right,rcEvent.bottom);			 
}

/*text lines up with lhs of window*/
//void PaintThread(CDCHandle hDC);
//#include <boost/thread/thread.hpp>
void PHScroll::DoPaint(CDCHandle hDC)
{	
	/*if(!phd._complete)
		return;

	boost::thread st(&PaintThread,hDC);
}

mutex draw_mtx;

void PaintThread(CDCHandle hDC)
{
	boost::mutex::scoped_lock sl(draw_mtx);*/
	CFont hFont;
	hFont.CreateFontA(12, 0, 0, 0, 400, FALSE, FALSE, 0,
                         ANSI_CHARSET, OUT_DEFAULT_PRECIS,
                         CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,
                         DEFAULT_PITCH ,"Arial" );
	CFont oldFont=		hDC.SelectFont(hFont);
	
	/*From the event map */
	COLORREF old_cr;
	old_cr=hDC.SetBkColor(0x00CA6002);
	
	CBrush ProcessBrush;
	ProcessBrush.CreateSolidBrush (RGB (GetRValue(0x00CA6002), GetGValue(0x00CA6002), GetBValue(0x00CA6002)));
	CBrush SelectedBrush;
	SelectedBrush.CreateSolidBrush (RGB(GetRValue(0x00CA6002),GetGValue(0x00CA6002),GetBValue(0x00606002)));
	COLORREF old_txt=hDC.SetTextColor(0x00FFFFFF);
		/*TODO:  tidy up logic*/
	/*Draw the processes*/
	for(map<long,RECT>::iterator it=phd._ProcessAreas.begin(); it!=phd._ProcessAreas.end(); it++)
	{
		RECT rcEvent;
		long lID=it->first;
		rcEvent=it->second;

		map<long,PHProcess>::iterator proc_it=		phq._Processes.find(lID);
		PHProcess pclProcess=proc_it->second;
					
		/* draw the process rectangle */
		
		if(phd._selected==lID)
		{
			if(hDC.FillRect(&rcEvent,SelectedBrush)==0)
				PHTrace(Win32Error(),__LINE__,__FILE__);
		}
		else
		{
			if(hDC.FillRect(&rcEvent,ProcessBrush)==0)
				PHTrace(Win32Error(),__LINE__,__FILE__);
		}
		
		DrawLines(hDC.m_hDC,rcEvent,lID);
			
		map<long,int>::iterator line_it=phq._Lines.find(lID);

		POINT pt;
		pt.x=rcEvent.left + 10;
		pt.y=(line_it->second*40)-20;
		map<long, long>::iterator crc_it=phq._PData.find(lID);
		map<long,string>::iterator image_it;
		if(crc_it!=phq._PData.end())
			image_it=phd._EXEImages.find(crc_it->second);

		string SystemName;
		if(image_it!=phd._EXEImages.end())
			SystemName=image_it->second;
		else
		{			
			map<long,string>::iterator qpit=phd.qrypaths.find(lID);
			if(qpit!=phd.qrypaths.end())
				SystemName=qpit->second;
		}
		/*Write system name at the correct location*/

		map<long,HICON>::iterator iconit;
		if(crc_it!=phq._PData.end())
			iconit=phd.icons.find(crc_it->second);
		if(iconit!=phd.icons.end())
		{
				//HDC iconDC;

			if(rcEvent.right-rcEvent.left>32)
			{
				HICON hIcon=iconit->second;
				if(hIcon!=NULL)
					if(hDC.DrawIcon(rcEvent.left+4,rcEvent.top+4,hIcon)==0)
						PHTrace(Win32Error(),__LINE__,__FILE__);
			}
			rcEvent.left+=37;
		}
		else
			rcEvent.left+=4;
		if(SystemName.length()>0)
		{
			/*fit the text to the rectangle at a constant font size*/
			COLORREF sel_cr;
			if(phd._selected==lID)
				sel_cr=hDC.SetBkColor(0x00606002);
			
			if(hDC.DrawText(SystemName.c_str(),SystemName.length(),&rcEvent,DT_LEFT|DT_VCENTER|DT_SINGLELINE)==0)
				PHTrace(Win32Error(),__LINE__,__FILE__);
			
			if(phd._selected==lID)
				hDC.SetBkColor(sel_cr);			
		}			
	}/*end process*/
	hDC.SetTextColor(old_txt);
	hDC.SetBkColor(old_cr);
	hDC.SelectFont(oldFont);
}

#include "..\background\icons.h"
#include <boost/filesystem.hpp>

void PHDisplay::ReadPaths()// base on paths.id avoids duplication 
{
	qrypaths.clear();

	unsigned long count=0;

	for(map<long,RECT>::iterator it=phd._ProcessAreas.begin(); it!=phd._ProcessAreas.end(); it++)
	{	
		count++;
		//::PostMessage (ph_instance._hWnd, UWM_DOWNLOAD_PROGRESS, count, _ProcessAreas.size() );
		sqlite3_stmt* stmt;
		sqlite3 *db=OpenDB();
		long lID=it->first;
		ostringstream os;
		os<<
		"SELECT Paths.Directory,Paths.ID FROM Process JOIN Paths ON Process.PathID=Paths.ID WHERE Process.ID=";
		os<<lID;
		os<<";";
		if(sqlite3_prepare(db,os.str().c_str(),-1,&stmt,NULL)!=SQLITE_OK)
			DBError(sqlite3_errmsg(db),__LINE__,__FILE__);
			
		if(sqlite3_step(stmt)== SQLITE_ROW )
		{
			//LPICONRESOURCE	lpIR;
			string FileName=(char*)sqlite3_column_text(stmt,0);
			//if(FileName.length()==0)
			//	continue;
			qrypaths.insert(pair<long,string>(lID,FileName));

			long PathID= sqlite3_column_int(stmt,1);
			phq._PData.insert(pair<long,long>(lID,PathID));
			if ( boost::filesystem::exists(FileName))
			{
			map<long,HICON>::iterator icon_it= icons.find(PathID);
			if(icon_it==icons.end())
			{
				LPICONRESOURCE lpIcoRes=ReadIconFromEXEFile(FileName.c_str()	);
				if(NULL!=lpIcoRes)
				{	
				        // For each image in the resoure
					for(int i=0;i<lpIcoRes->nNumImages;i++)
					{
						if(lpIcoRes->IconImages[i].Colors==32 && lpIcoRes->IconImages[i].Height==32)
						{
							HICON hIcon = MakeIconFromResource( &(lpIcoRes->IconImages[i]) );
							if(hIcon!=NULL)
								icons.insert(pair< long,HICON>(PathID,hIcon));
							else
								PHTrace("Extracting Icon failed "+Win32Error(),__LINE__,__FILE__);
						}//endif
					}//for
				}// end if
			 }
		
			 map<long,string>::iterator ver_it = phd._EXEImages.find(PathID);
			 if(ver_it==phd._EXEImages.end())
			 {
				string Product,Description;
				GetVersionInfo(Product,Description,FileName);	 
				if(!Product.empty() || !Description.empty())
				{
					phd._EXEImages.insert(pair< long,string>(PathID,Product));
				}
			 }
			}
		}//endif
		sqlite3_finalize(stmt);
		sqlite3_close(db);	
	}//for	
}
